package inabit.inabitcompiler.productions.rule.expressions.arithmetic;

import inabit.compiler.parser.grammar.NonTerminal;
import inabit.compiler.parser.grammar.Production;
import inabit.compiler.parser.grammar.Symbol;
import inabit.compiler.parser.grammar.Terminal;
import inabit.data.expression.arithmetic.ArithmeticExpression;
import inabit.data.expression.arithmetic.DivisionExpression;
import inabit.data.expression.arithmetic.MultiplicationExpression;
import inabit.inabitcompiler.lexical.InabitTokenClass;
import inabit.inabitcompiler.parser.InabitSemanticAction;

/**F' -> *FF'*/
/**@author Rafael Rocha*/
public class F1_Rule extends Production{
	private NonTerminal F;
	private NonTerminal F1;
	
	public F1_Rule() {
		super("F'");
	}
	
	public Symbol[] production(final NonTerminal nonTerminal) {
		F = new NonTerminal("F");
		F1 = new NonTerminal("F'");
		Symbol[] symbols = {
			new Terminal(InabitTokenClass.MULT),
			F,
			F1,
			new InabitSemanticAction(nonTerminal) {
				public void execute() throws Exception {
					nonTerminal.code = "*:";
					if(F1.code.isEmpty()) {
						nonTerminal.code += F.code;
					}else {
						ArithmeticExpression aExpr;
						String[] right = F1.code.split(":");
						String op = right[0];
						if(op.equals("*")) {
							aExpr = new MultiplicationExpression(
								getArithmeticExpression(F.code),
								getArithmeticExpression(right[1]));
						}else if(op.equals("/")){
							aExpr = new DivisionExpression(
								getArithmeticExpression(F.code),
								getArithmeticExpression(right[1]));
						}else {
							throw new Exception("Cant recognize operator " + op + " in this context ");
						}
						nonTerminal.code += addArithmeticExpressionAndGetCode(aExpr);
					}
				}
			}
		};
		return symbols;
	}
}
